<?php

namespace app\home\controller\subject;

use app\common\controller\Home;
use app\common\model\subject\Order;

class Teacher extends Home
{
    //不需要登录的方法
    protected $NoNeedLogin = ['index', 'info', 'subject','page'];

    // 定义课程模型
    protected $TeacherModel = null;

    protected $FollowModel = null;

    protected $SubjectModel = null;

    //课程分类模型
    protected $CategoryModel = null;

    //订单模型
    protected $OrderModel = null;

    //优惠卷模型
    protected $CouponModel = null;

    protected $RecordModel = null;

    protected $CommissionModel = null;

    //点赞模型
    protected $LikeModel = null;

    protected $BusinessModel = null;
    protected $ReceiveModel = null;

    // 构造函数
    public function __construct()
    {
        // 手动继承父级的构造函数
        parent::__construct();

        // 加载模型
        $this->TeacherModel = model('subject.Teacher');

        $this->FollowModel = model('subject.Follow');

        $this->SubjectModel = model('subject.Subject');

        $this->CategoryModel = model('subject.Category');

        $this->OrderModel = model('subject.Order');

        $this->CouponModel = model('coupon.Coupon');

        $this->LikeModel = model('subject.Like');
        $this->RecordModel = model('business.Record');
        $this->CommissionModel = model('business.Commission');
        $this->BusinessModel = model('business.Business');
        $this->ReceiveModel = model('coupon.Receive');
    }


    public function index()
    {
        if ($this->request->isAjax()) {
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            $search = $this->request->param('search', '', 'trim');

            $where = [];

            // 如果搜索关键字不为空
            if (!empty($search)) {
                // 组装条件
                $where['name|job'] = ['LIKE', "%$search%"];
            }

            $list = $this->TeacherModel->where($where)->page($page, $limit)->select();


            //查询数据总数
            $count = $this->TeacherModel->where($where)->count();

            $data = [
                'list' => $list,
                'count' => $count
            ];

            if ($list) {
                $this->success('查询老师成功', null, $data);
            } else {
                $this->error('暂无老师', null, $data);
            }
        }
        return $this->fetch();
    }


    public function info()
    {
        $teacherid = $this->request->param('teacherid', 0, 'trim');

        $info = $this->TeacherModel->find($teacherid);

        if (!$info) {
            $this->error('该老师不存在');
        }

        //首先拿登录用户id
        $business = $this->IsLogin(false);

        //定义默认关注状态
        $info['follow_status'] = false;

        if (!empty($business)) {
            $busid = $business['id'] ?? 0;

            $where = [
                'busid' => $busid,
                'teacherid' => $info['id']
            ];

            $follow = $this->FollowModel->where($where)->find();

            if ($follow) {
                $info['follow_status'] = true;
            } else {
                $info['follow_status'] = false;
            }
        }

        $this->assign([
            'info' => $info
        ]);
        return $this->fetch();
    }


    //处理当前老师的课程
    public function subject()
    {
        if ($this->request->isAjax()) {
            $teacherid = $this->request->param('teacherid', 0, 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit = $this->request->param('limit', 10, 'trim');
            $search = $this->request->param('search', '', 'trim');

            $teacher = $this->TeacherModel->find($teacherid);

            if (empty($teacher)) {
                $this->error("老师不存在");
            }

            $where = [
                'teacherid' => $teacherid
            ];

            if (!empty($where)) {
                $where['title'] = ['LIKE', "%$search%"];
            }

            $subjectlist = model('subject.Subject')->where($where)->page($page, $limit)->select();

            $count = model('subject.Subject')->where($where)->count();

            $data = [
                'list' => $subjectlist,
                'count' => $count
            ];

            if ($subjectlist) {
                $this->success('查询课程成功', null, $data);
            } else {
                $this->error('暂无课程', null, $data);
            }
        }
    }

    //老师的关注与取消关注
    public function follow()
    {
        if ($this->request->isAjax()) {

            $teacherid = $this->request->param('teacherid', 0, 'trim');
            // halt($teacherid);
            $busid = $this->auth->id ?? 0;

            $where = [
                'teacherid' => $teacherid,
                'busid' => $busid
            ];

            $teacher = $this->TeacherModel->find($teacherid);
            if (empty($teacher)) {
                $this->error('老师不存在');
            }

            $follow = $this->FollowModel->where($where)->find();

            if ($follow) {
                // halt("取消关注");
                // $result = $this->FollowModel->where($where)->delete();
                $result = $follow->delete();

                if ($result === true) {
                    $this->success("取消关注");
                } else {
                    $this->error("取消关注失败");
                }
            } else {
                $data = [
                    'teacherid' => $teacherid,
                    'busid' => $busid
                ];

                $result = $this->FollowModel->validate('common/teacher/Follow')->save($data);

                $this->assign([
                    'result' => $result
                ]);

                if ($result === false) {
                    $this->error($this->FollowModel->getError());
                } else {
                    $this->success("关注成功");
                }
            }
        }

        return $this->fetch();
    }

    //订单结算页面
    public function confirm()
    {
        //课程id
        $subid = $this->request->param('subject', '', 'trim');

        //用户id
        $busid = $this->auth->id ?? 0;

        $order = [
            'subid' => $subid,
            'busid' => $busid
        ];

        //查询课程
        $subject = $this->SubjectModel->find(['id' => $subid]);

        //查询课程老师
        $teacher = $this->TeacherModel->find(['id' => $subject['teacherid']]);

        //课程分类表
        $category = $this->CategoryModel->find(['id' => $subject['cateid']]);

        //查找优惠卷
        $coupon = $this->LikeModel->where($order)->find();
        if (!$coupon) {
            $this->error("优惠卷使用失败");
        }

        if ($coupon['cid'] != null) {
            $coupon = $this->CouponModel->where(['id' => $coupon['cid']])->find();
        } else {
            $coupon['rate'] = 1;
        }

        $total = bcmul($subject['price'], $coupon['rate'], 2);
        $subject['total'] = $total;

        if (!$subject) {
            $this->error("课程不存在");
        }

        //购买课程
        if ($this->request->isPost()) {
            //课程id
            $subid = $this->request->param('subject', '', 'trim');
            //用户id
            $busid = $this->auth->id ?? 0;
            //支付方式
            $pay = $this->request->param('pay', 'money', 'trim');

            $coupon = $this->request->param('coupon', '', 'trim');

            $order = [
                'subid' => $subid,
                'busid' => $busid,
                'pay' => $pay
            ];

            // 查询课程是否存在
            $subject = $this->SubjectModel->find(['id' => $subid]);

            if (!$subject) {
                $this->error('课程不存在');
            }

            // 课程价格
            $total = $subject['price'] ?? 0;

            // 查询优惠券是否已领取并且使用
            $receive = $this->ReceiveModel->with(['coupon'])->where(['receive.cid' => $coupon, 'receive.status' => '1', 'receive.receive' => '1'])->find();

            if ($receive) {
                $rate = $receive['coupon']['rate'] ?? 1;

                $total = bcmul($total, $rate, 2);
            } else {
                $total = $subject['price'];
            }

            // 判断支付方式是否为余额
            if ($pay == 'money') {

                // 开启事务
                $this->OrderModel->startTrans();
                $this->RecordModel->startTrans();
                $this->BusinessModel->startTrans();
                $this->ReceiveModel->startTrans();
                $this->CommissionModel->startTrans();

                // 封装订单数据
                $OrderData = [
                    'subid' => $subid,
                    'busid' => $busid,
                    'total' => $total,
                    'code' => build_code('ST'),
                    'createtime' => time(),
                    'couponid' => $coupon,
                    'pay' => $pay
                ];

                // 插入数据表
                $OrderStatus = $this->OrderModel->save($OrderData);

                if ($OrderStatus === false) {
                    $this->error($this->OrderModel->getError());
                }

                // 组装用户消费记录数据
                $RecordData = [
                    'total' => "-{$total}",
                    'content' => "购买课程：【{$subject['title']}】花费了 ￥{$total} 元",
                    'busid' => $busid
                ];

                // 插入数据
                $RecordStatus = $this->RecordModel->validate('common/business/Record')->save($RecordData);

                if ($RecordStatus === false) {  
                    $this->OrderModel->rollback();
                    $this->error($this->RecordModel->getError());
                }

                // 用户余额减去购买的金额
                $UpdateMoney = bcsub($this->auth->money, $total, 2);
                //判断余额是否足够
                if ($UpdateMoney < 0) {           
                    $this->error("余额不足，请重新支付");
                }
                $BusinessData = [
                    'id' => $this->auth->id,
                    'money' => $UpdateMoney
                ];

                //更新余额
                $BusinessStatus = $this->BusinessModel->validate('common/business/Business.pay')->isUpdate(true)->save($BusinessData);

                if ($BusinessStatus === false) {
                    $this->OrderModel->rollback();
                    $this->RecordModel->rollback();
                
                    $this->error('更新余额失败');
                }

                // 更新优惠券状态
                if ($receive) {
                 
                    $ReceiveData = [
                        'id' => $receive['id'],
                        'status' => 0
                    ];


                    $ReceiveStatus = $this->ReceiveModel->isUpdate(true)->save($ReceiveData);

                    if ($ReceiveStatus === false) {
                        $this->OrderModel->rollback();
                        $this->RecordModel->rollback();
                        $this->BusinessModel->rollback();

                        $this->error('更新优惠券状态失败');
                    }
                }

                // 当前用户是否有推荐人
                $parentid = $this->auth->parentid ?? 0;

                $business = $this->BusinessModel->where(['parentid' => $parentid])->find();

                if ($business) {
              
                    $AmountRate = config('site.AmountRate');

                    // 组装佣金记录
                    $CommissionData = [
                        'orderid' => $this->OrderModel->id,
                        'busid' => $this->auth->id,
                        'parentid' => $parentid,
                        'amount' => bcmul($total, $AmountRate,2),
                        'type' => 'subject',
                        'status' => 0,
                    ];

                    $CommissionStatus = $this->CommissionModel->validate('common/business/Commission')->save($CommissionData);

                    if ($CommissionStatus === false) {
                        
                        $this->OrderModel->rollback();
                        $this->RecordModel->rollback();
                        $this->BusinessModel->rollback();
                        $this->ReceiveModel->rollback();

                        $this->error($this->CommissionModel->getError());
                    }
                }

                if ($OrderStatus === false || $RecordStatus === false) {
                    $this->OrderModel->rollback();
                    $this->RecordModel->rollback();
                    $this->BusinessModel->rollback();
                    $this->ReceiveModel->rollback();
                    $this->CommissionModel->rollback();

                    $this->error('购买课程失败');
                } else {
                    $this->OrderModel->commit();
                    $this->RecordModel->commit();
                    $this->BusinessModel->commit();
                    $this->ReceiveModel->commit();
                    $this->CommissionModel->commit();
                    $this->success('购买课程成功', url("/home/index/collect?subject=$subid"));
                }
            } else {
                $domain = $this->request->domain();
                //携带自定义参数
                $third = [
                    'busid' => $this->auth->id,
                    'subid' => $subid,
                    'coupon' => $coupon
                ];

                $payArr = ['wx', 'zfb'];

                if (!in_array($pay, $payArr)) {
                    $this->error('未知支付方式');
                }

                $params = [
                    'name' => "购买【课程的{$subject['title']}】支付订单",
                    'third' => json_encode($third),
                    'paytype' => $pay === 'wx' ? '0' : '1',
                    'originalprice' => $total,
                    'paypage' => 1,
                    'reurl' => url('/home/pay/notice', ['subid' => $subid], true, true),
                    'callbackurl' => $domain . '/home/pay/callback',
                    'wxcode' => $domain . config('site.wxcode'),
                    'zfbcode' => $domain . config('site.zfbcode')
                ];

                // 拼接创建订单接口
                $create_order_url = $domain . '/pay/index/create';

                $result = HttpRequest($create_order_url, $params);

                // 支付页面
                echo $result;
                exit;
            }
        }

        $this->assign([
            'subject' => $subject,
            'teacher' => $teacher,
            'category' => $category,
            'coupon' => $coupon
        ]);

        return $this->fetch();
    }
}
